import { Message } from 'element-ui'

const copy = {
  bind(el, binding) {
    el.copyData = binding.value
    const { arg, modifiers } = binding
    
    // 设置提示文本
    el.title = modifiers.tooltip ? '点击复制' : ''
    
    // 设置复制成功的回调
    el.copySuccess = arg === 'success' ? () => {
      Message.success('复制成功')
    } : null
    
    // 添加复制样式
    if (modifiers.pointer) {
      el.style.cursor = 'pointer'
    }
    
    el.addEventListener('click', handleClick)
  },
  
  update(el, binding) {
    el.copyData = binding.value
  },
  
  unbind(el) {
    el.removeEventListener('click', handleClick)
  }
}

function handleClick(event) {
  const copyText = typeof this.copyData === 'object' ? 
    JSON.stringify(this.copyData, null, 2) : 
    this.copyData.toString()

  // 使用新的 Clipboard API
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(copyText).then(() => {
      this.copySuccess ? this.copySuccess() : Message.success('复制成功')
    }).catch(() => {
      fallbackCopyText(this, copyText)
    })
  } else {
    fallbackCopyText(this, copyText)
  }
}

// 降级复制方案
function fallbackCopyText(el, text) {
  const input = document.createElement('input')
  input.value = text
  input.style.position = 'fixed'
  input.style.opacity = '0'
  document.body.appendChild(input)
  input.select()
  
  try {
    document.execCommand('copy')
    el.copySuccess ? el.copySuccess() : Message.success('复制成功')
  } catch (err) {
    Message.error('复制失败')
    console.error('复制失败:', err)
  } finally {
    document.body.removeChild(input)
  }
}

export default copy 